// pages/settleIn/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:'',
    price:'',
    type:'分类错误会影响审核结果，请仔细确认',
    latitude:'',
    address:'',
    userName:'',
    mobile:'',
    columns: [],
    typeList:[],
    isPopup:false,
    isTip:false,
    typeId:'',
    image:'https://huitongkeji.oss-cn-shenzhen.aliyuncs.com/1715581524442.png',
    storeImage:'https://huitongkeji.oss-cn-shenzhen.aliyuncs.com/1715753286207.png',
    tabList:[
      {name:'周一',status:false},
      {name:'周二',status:false},
      {name:'周三',status:false},
      {name:'周四',status:false},
      {name:'周五',status:false},
      {name:'周六',status:false},
      {name:'周日',status:false}
    ],
    reservation:[
      {
        name:'无需预约',
        val:0
      },
      {
        name:'需要预约',
        val:1
      },
    ],//预约
    productIds:[],
    useNotice:'',
    arr:[],
    arrList:[],
    package:{
      productIds:[],
      needPre:-1
    },
    list:[]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.typeList()
    if(options.id){
     
    }else{
   
    }
    if(options && options.id){
      this.setData({
        id:parseInt(options.id)
      })
      wx.setNavigationBarTitle({
        title: '编辑套餐',
      })
      this.getDetail()
    }else{
      console.log('onLoad======')
      wx.setNavigationBarTitle({
        title: '添加套餐',
      })
      this.storePackageProList()
    }
    
  },
  typeList(){
    app.agriknow.getClickList().then(res=>{
      console.log(res)
      let columns = []
      res.data.forEach((item,index)=>{
        columns.push(item.name)
      })
      this.setData({
        typeList:res.data,
        columns:columns
      })
    })
  },
  
  submit(){
    wx.showLoading({
      title: '上传中',
      mask:true
    })
    if(!this.data.name) return this.tip('请输入套餐名称');
    if(!this.data.price) return this.tip('请输入套餐价格');
    if(!this.data.marketPrice) return this.tip('请输入套餐门市价格');
    if(!(this.data.needPre>=0)) return this.tip('请选择是否需要预约');
    if(!this.data.describe) return this.tip('请填写描述');
    if(this.data.arrList.length==0) return this.tip('请添加产品');
    if(this.data.image=='https://huitongkeji.oss-cn-shenzhen.aliyuncs.com/1715581524442.png') return this.tip('请上传缩略图');
    
    let data = {
      name:this.data.name,
      price:this.data.price,
      marketPrice:this.data.marketPrice,
      image:this.data.image,
      needPre:this.data.needPre,
      describe:this.data.describe,
      productIds:this.data.productIds,
      storeId:wx.getStorageSync('userInfo').storeId
    }
    //type	1:爆品推荐；2：理我最近；3：无须预约
    app.agriknow.storeAddPackage(data).then(res=>{
      console.log(res)
      wx.hideLoading()
      if(res.code=='000000'){
        wx.showModal({
          title: '提示',
          content: '提交成功',
          showCancel:false,
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      }
    }).catch(res=>{
      wx.hideLoading()
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000,
        mask: true
      })
    })
  },
  upload(e) {
    let that = this
    let index = e.currentTarget.dataset.index
    wx.chooseMedia({
      count:1,
      success (res) {
        console.log(res.tempFiles[0].tempFilePath)
        const tempFilePaths = res.tempFiles[0].tempFilePath
        wx.uploadFile({
          url: app.agriknow._baseUrl+'ht/user/uploadImage', //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success (res){
            console.log(res)
            if(index==1){
              that.setData({
                image:JSON.parse(res.data).data
              })
            }
            
          }
        })
      }
    })
  },
  // onCancel(e){
  //   console.log(e)
  //   this.setData({
  //     isPopup:false
  //   })
  // },
  // onConfirm(e){
  //   console.log('1',e.detail.index)
  //   this.setData({
  //     isPopup:false,
  //     type:e.detail.value,
  //     typeId:this.data.typeList[e.detail.index].id
  //   })
  // },
  openPopup(){
    this.setData({
      isPopup:true
    })
  },
  openTip(){
    this.setData({
      isTip:true
    })
  },
  tip(name){
    wx.showToast({
      title: name,
      icon:'none',
      duration: 2000
    })
  },
  tipClick(e){
    let index = e.currentTarget.dataset.index
    let tabList = this.data.tabList
    tabList[index].status = !tabList[index].status
    this.setData({
      tabList:tabList
    })
    console.log(tabList)
  },
  allSure(){
    let tabList = this.data.tabList
    tabList.forEach((item,index)=>{
      item.status = true
    })
    this.setData({
      tabList:tabList
    })
  },
  isOk(){
    console.log(1)
    let useNotice = []
    this.data.tabList.forEach((item,index)=>{
      if(item.status){
        useNotice.push(item.name)
      }
    })
    this.setData({
      isTip:false,
      useNotice:useNotice.join(',')
    })
  },
  addPackageProduct(){
    let that = this
    wx.navigateTo({
      url: '/pages/addPackageProduct/index',
      success:function(res){
        res.eventChannel.emit('addPackageProduct', {arr:that.data.arr})
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(wx.getStorageSync('arr')){
      let arr = wx.getStorageSync('arr')
      let productIds = []
      let arrList = []
      arr.forEach((item,index)=>{
        if(item.checked==true){
          arrList.push(item)
          productIds.push({
            number:item.number,
            productId:item.id
          })
        }
      })
      this.setData({
        productIds:productIds,
        arr:arr,
        arrList:arrList
      })
      console.log(this.data.productIds)
      wx.setStorageSync('arr', '')
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  input:function(e){
    console.log(e)
    var key='package.'+e.currentTarget.dataset.key
    var val=e.detail.value
    this.setData({
      [key]:val
    })
  },
  changePicker:function(e){
    console.log(e)
    var key='package.'+e.currentTarget.dataset.key
    var val=e.detail.value
    
    this.setData({
      [key]:val
    })
  },

  storePackageProList(){
    var that=this
    let data = {
      storeId:wx.getStorageSync('userInfo').storeId
    }
    
    var id=this.data.id
    var packageJson=this.data.package
    var productIds=packageJson.productIds
    app.agriknow.storePackageProList(data).then(res=>{
      console.log(res)
      let list = res.data
 
      list.forEach((item,index)=>{
        var idsIndex=productIds.findIndex(ite=> item.id==ite.productId)
        if(idsIndex>-1){
          item.number = productIds[idsIndex].num,
          item.checked=true
        }else{
          item.number = 1,
          item.checked=false
        }
        
      })
      that.setData({
        list:list
      })
      console.log(this.data.list)
    })
  },

  uploadImg(e) {
    let key = 'package.'+e.currentTarget.dataset.name
    let that = this
    wx.chooseMedia({
      count:1,
      success (res) {
        console.log(res.tempFiles[0].tempFilePath)
        const tempFilePaths = res.tempFiles[0].tempFilePath
        wx.uploadFile({
          url: app.agriknow._baseUrl+'ht/user/uploadImage', //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success (res){
            that.setData({
              [key]:JSON.parse(res.data).data
            })
            
          }
        })
      }
    })
  },
  formSubmit:function(){
    var data={}
    data=this.data.package
    var tips=''
    if(!data.name){
        tips='请输入套餐名称'
    }else if(!data.price){
        tips='请输入产品价格'
    }else if(!data.marketPrice){
      tips='请输入门市价格'
    }else if(Number(data.price)>Number(data.marketPrice)){
      tips='套餐价格不能高于门市价格'
    }else if(data.needPre<0){
      tips='请选择是否需要预约'
    }else if(!data.describe){
      tips='请输入套餐描述'
    }else if(data.productIds.length==0){
      tips='请添加产品'
    }else if(!data.image){
      tips='请上传套餐缩略图'
    }else if(!data.bannerImage){
      tips='请上传套餐主图'
    }else if(!data.detailsImage){
      tips='请上传套餐详情图'
    }
    if(tips){
      wx.showToast({
        title: tips,
        icon:'none',
        duration:1500,
        mask:true
      })
      return false
    }
 
    data.storeId=wx.getStorageSync('userInfo').storeId
    var id=this.data.id
    var url=''
    var mgs=''
    if(id){
      data.packageId=id
      url='/ht/store/storeUpdPackage'
      mgs='编辑'
      

    }else{
      url='/ht/store/storeAddPackage'
      mgs='添加'
    }
    app.agriknow.commRequest(url,data).then(res=>{
      if(res.code=='000000'){
        wx.showToast({
          title: mgs+'成功',
          icon:'none',
          duration:1500,
          mask:true
        })
        setTimeout(function(){
          wx.navigateBack()
        },1500)
      }else{
        wx.showToast({
          title: mgs+'失败',
          icon:'none',
          duration:1500,
          mask:true
        })
      }
    })
  },
  getDetail:function(){
    var that=this
    var data={}
    data.id=this.data.id
    app.agriknow.commRequest('ht/store/packageDetails',data).then(res=>{
      this.setData({
        package:res.data
      })
      that.storePackageProList()
    })
  }
})